/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.itip.collector;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.jms.JMSException;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.sinodata.bsm.common.vo.CollectField;
import com.sinodata.bsm.common.vo.Property;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResPropertyValue;
import com.sinodata.bsm.common.vo.ResPropertyValue.PropValue;
import com.sinodata.bsm.itip.cache.CacheFactory;
import com.sinodata.bsm.itip.cache.CollectFieldCache;
import com.sinodata.bsm.itip.cache.PropertyCache;
import com.sinodata.bsm.itip.cache.ResCache;
import com.sinodata.bsm.itip.message.Messenger;
import com.sinodata.bsm.itip.tivoli.ConfInfo;
import com.sinodata.bsm.itip.tivoli.ConfManager;
import com.sinodata.bsm.itip.tivoli.TivoliPropBean;
import com.sinodata.bsm.itip.util.DB2ConnectionUtil;
import com.sinodata.bsm.itip.util.SystemContext;
import com.sinodata.bsm.itip.util.TivoliConstants;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-8-2 下午12:49:01          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class UnixJob implements Job {

    private static final Logger logger = Logger.getLogger(UnixCollector.class);

    private ResCache resCache = (ResCache) CacheFactory.getCache(ResCache.class);

    private PropertyCache propertyCache = (PropertyCache) CacheFactory.getCache(PropertyCache.class);

    private CollectFieldCache fieldCache = (CollectFieldCache) CacheFactory.getCache(CollectFieldCache.class);

    private static final SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddhhmmss");

    String groupType = "";

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("[TIP]\t Fetch Props From Tivoli ");

        ConfInfo conf = ConfManager.getInstance().getConfMap().get("2201030200000");

        //采集到指标值
        List<TivoliPropBean> tivoliList = fetchPorpFromWarehous(conf);

        //发送指标
        sendPropValues(tivoliList, conf);
    }

    /**
     * 1：根据返顺结果第一列的值(iid)查找资源，有值则组装成可用指标  无值则抛弃
     * 2：每一条指标  启用一次Messager的消息发送
     * 3: 修改了指标组装方式   因数据库中的采集相关脚本  只是针对实时指标采集数据的
     * @param values
     */
    private void sendPropValues(List<TivoliPropBean> beans, ConfInfo conf) {
        if (beans == null) {
            return;
        }
        for (TivoliPropBean bean : beans) {
            String[] props = conf.getProps().split("[,]");
            if (props.length != bean.getValues().length) {
                continue;
            }
            ResPropertyValue value = new ResPropertyValue();
            //resid
            Long resId = resCache.getResIdByIId(bean.getKey()).getId();
            if (resId == null) {
                continue;
            }
            value.setResId(resId);

            //
            value.setTaskId(-1L);

            //time
            value.setTime(new Date());
            //value
            List<PropValue> propValueList = new ArrayList<PropValue>();
            for (int i = 0; i < props.length; i++) {
                Long propId = Long.parseLong(props[i]);
                Property property = propertyCache.get(propId);
                if (property == null) {
                    continue;
                }
                CollectField field = fieldCache.getByPropId(propId);
                PropValue propValue = ResPropertyValue.createPropValue(propId, bean.getValues()[i], field.getFieldName());
                propValueList.add(propValue);
            }
            value.setValues(propValueList.toArray(new PropValue[propValueList.size()]));
            sendPropertyValue(value);
        }
    }

    public String matchRes(TivoliPropBean bean) {
        String resId = "";

        return resId;
    }

    /**
     * 对取到的指标值做校验  如果指标值有对应的资源则保留 否则删除 
     * @param propList
     * @param resList
     * @return
     */
    List<ResPropertyValue> check(List<String[]> propList, List<Res> resList) {
        List<ResPropertyValue> list = new ArrayList<ResPropertyValue>();
        return list;
    }

    /**
     * 查询指标数据
     * @param groupType
     * @param begintIME
     * @param endTime
     * @return
     */
    public List<TivoliPropBean> fetchPorpFromWarehous(ConfInfo conf) {
        String sql = replaceSqlParam(conf.getSql());
        //todo test
        System.out.println(sql);
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        ResultSetMetaData rsMetaData = null;
        List<TivoliPropBean> values = new ArrayList<TivoliPropBean>();
        try {
            conn = DB2ConnectionUtil.getInstance().getConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            if (rs == null) {
                return null;
            }
            rsMetaData = rs.getMetaData();
            int numberOfColumns = rsMetaData.getColumnCount();
            while (rs.next()) {
                TivoliPropBean bean = new TivoliPropBean();
                bean.setKey(rs.getString(1));
                for (int i = 2; i <= numberOfColumns; i++) {
                    String[] value = new String[numberOfColumns - 1];
                    value[i - 2] = rs.getString(i);
                    bean.setValues(value);
                }
                values.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                }
            }
            DB2ConnectionUtil.getInstance().returnConn(conn);
        }
        return values;
    }

    /**
     * 替换sql中的变量 并设置
     * @param str
     * @return
     */
    private String replaceSqlParam(String str) {
        str = str.replaceAll("\\{ST\\}", SystemContext.getProperty(TivoliConstants.BEGINTIME, "").toString());
        str = str.replaceAll("\\{ET\\}", SystemContext.getProperty(TivoliConstants.ENDTIME, "").toString());
        return str;
    }

    /**
     * 构建查询语句  
     * @return  
     * 第一列是主机名 第二列是资源的唯一标识符    这两个对应资源的唯一标识符
     */
    @SuppressWarnings("unused")
    private String buildSql() {
        Calendar now = Calendar.getInstance();

        StringBuilder sb = new StringBuilder("select \"System_Name\",\"CPU_ID\",\"User_CPU\",\"User_Nice_CPU\" from itmuser.\"KLZ_CPU\"");
        String table = getTableName(groupType);
        sb.append(table);
        String beginTime = (String) SystemContext.getProperty(TivoliConstants.BEGINTIME, "");
        if (beginTime == null || beginTime.length() == 0) {
            return null;
        } else {
            sb.append(" where \"Timestamp\" >= '1120807152000000'");
        }
        String endTime = sf.format(now.getTime());
        SystemContext.setProperty("beginTime", endTime);
        sb.append(" and \"Timestamp\" < '1120808100011000'");
        return sb.toString();
    }

    /**
     * 根据资源类别组 获取  表名
     * @param type
     * @return
     */
    String getTableName(String type) {
        return "kfwisit";
    }

    /**
     * 发送实时指标值到center的队列中。
     */
    private void sendPropertyValue(ResPropertyValue valuex) {
        //        System.out.println(valuex);
        try {
            Messenger.getInstance().sendPropertyValue(valuex);
        } catch (JMSException e) {
            logger.error("failed to send property value:" + valuex, e);
        }
    }

    public static void main(String[] args) {
        //        Calendar now = Calendar.getInstance();
        //        Date dd = new Date();
        //        //        Timestamp nousedate = new Timestamp(now.getTimeInMillis()); 
        //        Timestamp nousedate = new Timestamp(dd.getTime());
        //
        //        System.out.println(nousedate);
        //
        //        System.out.println(System.currentTimeMillis());

        String str = "select  \"Timestamp\" >= {ST} and Timestamp < {ET}";
        str = str.replaceAll("\\{ST\\}", "0090999");
        System.out.println(str);

    }
}
